package com.baseproject.mvp;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.baseproject.BaseActivity;
import com.baseproject.BaseApplication;
import com.baseproject.IRxSubscriberRefresh;
import com.baseproject.IRxSubscriberView;
import com.baseproject.datasource.RepositoryComponent;
import com.baseproject.mvp.delegate.ActivityMvpDelegate;
import com.baseproject.mvp.delegate.ActivityMvpDelegateImpl;
import com.baseproject.mvp.delegate.MvpDelegateCallback;

/**
 * Created by hp on 2017/6/8.
 */

public abstract class MvpActivity<V extends MvpActivity, P extends MvpBasePresenter<V>> extends BaseActivity
        implements MvpView, MvpDelegateCallback<V, P>, IRxSubscriberView{

    @Override
    public String getPurpose() {
        return mJumpCallbackHelper.getPurpose();
    }

    @Override
    public Context getContext() {
        return getContext();
    }

    @Override
    public IRxSubscriberRefresh getRefresh() {
        return null;
    }

    public P mPresenter;

    protected ActivityMvpDelegate mvpDelegate;
    protected RepositoryComponent mRepositoryComponent;

    private void setComponent() {
        mRepositoryComponent = BaseApplication.getApplication().getRepositoryComponent();
    }

    /**
     * Get the mvp delegate. This is internally used for creating presenter, attaching and detaching
     * view from presenter.
     *
     * <p><b>Please note that only one instance of mvp delegate should be used per Activity
     * instance</b>.
     * </p>
     *
     * <p>
     * Only override this method if you really know what you are doing.
     * </p>
     *
     * @return {@link ActivityMvpDelegateImpl}
     */
    @NonNull
    protected ActivityMvpDelegate<V, P> getMvpDelegate() {
        if (mvpDelegate == null) {
            mvpDelegate = new ActivityMvpDelegateImpl<>(this, this);
        }
        return mvpDelegate;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setComponent();
        initStatusBar();
        getMvpDelegate().onCreate(savedInstanceState);
    }

    protected void initStatusBar() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getMvpDelegate().onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        getMvpDelegate().onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        getMvpDelegate().onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getMvpDelegate().onDestroy();
    }

    @Override
    public void setPresenter(P presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public P getPresenter() {
        return this.mPresenter;
    }

    @Override
    public V getMvpView() {
        return (V) this;
    }
}
